import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { api, type UserInfo, type LoginRequest, type LoginResponse } from '@/api'

export const useUserStore = defineStore('user', () => {
  // 状态
  const userInfo = ref<UserInfo | null>(null)
  const token = ref<string>('')
  const notificationCount = ref<number>(0)
  const isLoading = ref<boolean>(false)

  // 计算属性
  const isLoggedIn = computed(() => !!token.value && !!userInfo.value)
  const userName = computed(() => userInfo.value?.userNickname || userInfo.value?.userName || '')
  const userPhone = computed(() => userInfo.value?.phone || '')
  const userAvatar = computed(() => userInfo.value?.avatar || '')
  const medicalCardBalance = computed(() => userInfo.value?.balance || 0)
  const userRole = computed(() => userInfo.value?.roleName || '')
  const userPermissions = computed(() => userInfo.value?.permissions || [])

  // 动作
  const setToken = (newToken: string) => {
    token.value = newToken
    api.setToken(newToken)
    // 保存到本地存储
    localStorage.setItem('token', newToken)
  }

  const clearToken = () => {
    token.value = ''
    api.setToken('')
    localStorage.removeItem('token')
  }

  const setUserInfo = (info: UserInfo) => {
    userInfo.value = info
  }

  const clearUserInfo = () => {
    userInfo.value = null
  }

  // 登录
  const login = async (loginData: LoginRequest) => {
    isLoading.value = true
    console.log('开始登录，登录数据:', loginData)
    
    try {
      const response = await api.login(loginData)
      console.log('登录API响应:', response)
      
      // 检查响应码，后端返回100表示成功
      if (response.code === 100) {
        const loginResponse: LoginResponse = response.data
        console.log('登录成功，用户数据:', loginResponse)
        
        // 构造用户信息
        const userInfo: UserInfo = {
          userId: loginResponse.userId,
          userName: loginResponse.userName,
          userNickname: loginResponse.userNickname,
          roleId: loginResponse.roleId,
          roleName: loginResponse.roleName,
          token: loginResponse.token,
          permissions: loginResponse.permissions,
          avatar: '', // 后端没有返回头像，使用默认值
          phone: '', // 后端没有返回手机号，使用默认值
          medicalCardNo: '', // 后端没有返回就诊卡号，使用默认值
          balance: 0, // 后端没有返回余额，使用默认值
          createTime: loginResponse.createTime || ''
        }
        
        setToken(loginResponse.token)
        setUserInfo(userInfo)
        
        console.log('用户信息已保存:', userInfo)
        return { success: true, message: response.message || '登录成功' }
      } else {
        console.error('登录失败，响应码:', response.code, '消息:', response.message)
        return { success: false, message: response.message || '登录失败' }
      }
    } catch (error) {
      console.error('登录异常:', error)
      return { success: false, message: '登录失败，请检查用户名和密码' }
    } finally {
      isLoading.value = false
    }
  }

  // 登出
  const logout = () => {
    clearToken()
    clearUserInfo()
    notificationCount.value = 0
  }

  // 获取用户信息
  const fetchUserInfo = async () => {
    if (!token.value) return

    try {
      // const response = await api.getUserProfile()
      // setUserInfo(response.data)
    } catch (error) {
      console.error('获取用户信息失败:', error)
      // 如果token无效，清除登录状态
      if (error instanceof Error && error.message.includes('401')) {
        logout()
      }
    }
  }

  // 获取通知数量
  const fetchNotificationCount = async () => {
    if (!token.value) return

    try {
      const response = await api.getNotificationCount()
      notificationCount.value = response.data.count
    } catch (error) {
      console.error('获取通知数量失败:', error)
    }
  }

  // 更新用户信息
  const updateUserInfo = async (updateData: Partial<UserInfo>) => {
    if (!token.value) return

    try {
      // TODO: 实现更新用户信息API
      // const response = await api.updateUserProfile(updateData)
      // setUserInfo(response.data)
      
      // 模拟更新成功
      if (userInfo.value) {
        setUserInfo({ ...userInfo.value, ...updateData })
      }
      
      return { success: true, message: '更新成功' }
    } catch (error) {
      console.error('更新用户信息失败:', error)
      return { success: false, message: '更新失败' }
    }
  }

  // 初始化 - 从本地存储恢复token
  const initialize = () => {
    const savedToken = localStorage.getItem('token')
    if (savedToken) {
      setToken(savedToken)
      // 注释掉自动获取用户信息，避免调用未开发的接口
      // fetchUserInfo()
      // fetchNotificationCount()
    }
  }

  return {
    // 状态
    userInfo,
    token,
    notificationCount,
    isLoading,
    
    // 计算属性
    isLoggedIn,
    userName,
    userPhone,
    userAvatar,
    medicalCardBalance,
    userRole,
    userPermissions,
    
    // 动作
    setToken,
    clearToken,
    setUserInfo,
    clearUserInfo,
    login,
    logout,
    fetchUserInfo,
    fetchNotificationCount,
    updateUserInfo,
    initialize
  }
})